<template>
  <div class="el_breadcrumb">
    <el-tabs
      v-model="activeTab"
      closable
      type="card"
      @tab-remove="removeTab"
      @tab-click="clickBtn"
    >
      <el-tab-pane
        :key="item.path"
        v-for="item in tabList"
        :label="item.title"
        :name="item.path"
      >
      <!-- <i :class="item.icon"></i> &nbsp;&nbsp; -->
        <span slot="label"
          >{{ item.title }}</span
        >
        {{ item.content }}
      </el-tab-pane>
    </el-tabs>
  </div>
</template>


<script>
import store from "@/store";
export default {
  name: "historyRouter",
  data() {
    return {
      // 当前活跃的tabs
      activeTab: "",
    };
  },
  computed: {
    tabList() {
      return store.getters["tabList"];
    },
  },
  watch: {
    $route: function () {
      this.setActiveTab();
      this.addTab();
    },
  },
  mounted() {
    this.beforeRefresh();
    this.setActiveTab();
    this.addTab();
  },
  methods: {
    // 设置活跃的tab路由
    setActiveTab() {
      this.activeTab = this.$route.path;
    }, // 添加tab
    addTab() {
      const { path, meta } = this.$route;
      const tab = {
        path,
        title: meta.title,
        icon: meta.icon,
      };
      store.commit("app/ADD_TAB", tab);
      sessionStorage.setItem("tabsView", JSON.stringify(this.tabList));
    },
    // 点击tab
    clickBtn(tab) {
      const { name } = tab;
      this.$router.push({ path: name });
    },
    // 删除tab
    removeTab(target) {
      // 当前激活的tab
      let active = this.activeTab;
      let tabs = this.tabList;
      // 只有一个标签页的时候不允许删除
      if (tabs.length === 1) return;
      if (active === target) {
        tabs.forEach((tab, index) => {
          if (tab.path == target) {
            // 如果删除的就是当前活跃的tab,就把活跃的tab变成上一个或下一个
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              active = nextTab.path;
              this.activeTab = active;
              this.$router.push(this.activeTab);
            }
          }
        });
      }
      // 重新设置当前激活的选项卡和 选项卡列表

      store.commit(
        "app/REMOVE_TAB",
        tabs.filter((tab) => tab.path !== target)
      );
      sessionStorage.setItem("tabsView", JSON.stringify(this.tabList));
    },
    // 解决刷新数据丢失问题
    beforeRefresh() {
      let tabSession = sessionStorage.getItem("tabsView");
      if (tabSession) {
        let oldTabs = JSON.parse(tabSession);
        if (oldTabs.length > 0) {
          store.commit("app/REMOVE_TAB", oldTabs);
        }
      }
    },
  },
};
</script>

<style lang="scss">

</style>